#!/usr/bin/env python
# -*- coding: utf-8 -*-

from queue import Queue, Empty
import time
from threading import Thread, Lock
import datetime
from .tools import to_hex_list
from .tools import singleton
import logging
_logger = logging.getLogger(__name__)


@singleton
class Message(Thread):
    # 串口接收数据的后续处理
    # 单独启动一个线程, 管理串口的后续操作: 调串口发送, 读本地数据库, 访问服务器

    def __init__(self, rxd_cb):
        # 参数. 回调函数
        Thread.__init__(self,)
        self.queue = Queue()
        self.lock = Lock()
        self.rxd_cb = rxd_cb

    def lockedstart(self):
        with self.lock:
            if not self.isAlive():
                self.daemon = True
                self.start()

    def put(self, cmd, data):
        # 被串口接收线程调用, 将串口处理过头尾后的数据 送到这里, 排队处理
        # 参数, 命令字 + 数据
        #
        # print('msg put, ', msg)
        self.lockedstart()
        self.queue.put((cmd, data))

    def run(self):
        while True:
            try:
                # print(datetime.datetime.now(), 'message run, 1, ')
                # 这里 会 pending
                cmd, data = self.queue.get(True)
                _logger.debug('+++cmd=%s, data=%s' %
                              (hex(cmd), to_hex_list(data)))

                # print(datetime.datetime.now(), 'message rxd,', cmd, data)
                # 收到数据后, call 回调函数, 进行后续操作
                self.rxd_cb(cmd, data)
                pass
            except Exception as e:
                _logger.error('Error: %s' % str(e))
                print('Error: %s' % str(e))


if __name__ == '__main__':

    pass

    # print(datetime.datetime.now(), 'main ,0 ', datetime.datetime.now())
    # uart = Message()
    # print(datetime.datetime.now(), 'main ,1 ', datetime.datetime.now())
    # uart.rcv_data(111)
    # print(datetime.datetime.now(), 'main ,2 ', datetime.datetime.now())
    # time.sleep(2)
    # print(datetime.datetime.now(), 'main ,3 ', datetime.datetime.now())
    # uart.rcv_data(223)
    # print(datetime.datetime.now(), 'main ,4 ', datetime.datetime.now())

    # time.sleep(20)
